const fs = require('fs');
var iconv = require('iconv-lite');

var filePath = './sj.txt';


var bufs = [];

var readStream = fs.createReadStream(filePath);

//open是ReadStream对象中表示文件打开时事件，
readStream.on('open', function (fd) {
  console.log('开始读取文件' + fd);
});


readStream.on('data', function (chunk) {
  bufs.push(chunk);
  // buf = Buffer.concat([buf, chunk], buf.length+chunk.length);
});

readStream.on('error', function (err) {
  console.error(err);
});

//暂停和回复文件读取；
readStream.on('open', function () {
  console.log('开始读取文件');
});

readStream.on('end', function () {
  console.log('读取文件结束');

  // 接收数据结束后，拼接所有收到的Buffer对象
  var buf = Buffer.concat(bufs);

  dealRead(buf);
});

readStream.on('close', function () {
  console.log('文件关闭');
});


// 判断大写16进制与数字
function isAF09(value) {
  return (value >= 0X30 && value <= 0X39)
    || (value >= 0X41 && value <= 0X46);
}


// 16进制与数字转真是数字
function getAF09(value) {
  if (value >= 0X30 && value <= 0X39) {
    return value - 0X30;
  }

  if (value >= 0X41 && value <= 0X46) {
    return value - 0X41 + 10;
  }

  throw 'error value';
}


function dealRead(bufIn) {
  console.log(bufIn.length);


  var bufOut = new Buffer(0);

  var ixIn = 0;
  var length = bufIn.length;

  const MAX = 1024;
  var bufTmp = Buffer.allocUnsafe(1024).fill(0);
  var ixOut = 0;

  var cix = 0; // 统计

  console.log(bufIn.slice(0, 2).toString('ascii'));
  while (ixIn + 1 < length) {
    if (isAF09(bufIn[ixIn]) && isAF09(bufIn[ixIn + 1])) {

      // 写满了
      if (ixOut >= MAX) {
        bufOut = Buffer.concat([bufOut, bufTmp]);
        ixOut = 0;
        bufTmp.fill(0);
      }

      bufTmp.writeUInt8(getAF09(bufIn[ixIn]) * 16 + getAF09(bufIn[ixIn + 1]), ixOut);
      ixOut++;

      cix++;
      ixIn++;
    }

    ixIn++;
  }

  if (ixOut > 0) {
    bufOut = Buffer.concat([bufOut, bufTmp.slice(0, ixOut)]);
  }

  console.log("ok  length:" + bufOut.length);

  console.log("length:" + length);
  console.log("count:" + cix);


  var strOut = iconv.decode(bufOut, 'gb2312');


  console.log("-----------");
  console.log(strOut);

}


